package page

import (
	"ibdreader/slice"
)

/**
 * XDES entry in XDES pages/FSP_HDR
 * 40 byte (40*256)
 */

type Xdes struct {
	segmentId int64

	/**
	 * List node for XDES list: Pointers to previous and next extents in a doubly-linked
	 * extent descriptor list.
	 * 指向前后extent的指针，所有extent双向链接。
	 */
	xdesListNode ListNode

	/**
	 * State: extent的空闲状态。The current state of the extent, for which only four values
	 * are currently defined: FREE, FREE_FRAG, and FULL_FRAG, meaning this extent belongs to
	 * the space’s list with the same name; and FSEG, meaning this extent belongs to the file
	 * segment with the ID stored in the File Segment ID field.
	 */
	state XdesState

	/**
	 * Page State Bitmap: page空闲情况。A bitmap of 2 bits per page in the extent (64 x 2 = 128 bits,
	 * or 16 bytes). The first bit indicates whether the page is free. The second bit is reserved
	 * to indicate whether the page is clean (has no un-flushed data), but this bit is currently
	 * unused and is always set to 1.
	 */
	pageStateBitmap []byte
}

func XdesReadSlice() Xdes {
	var xdes Xdes
	xdes.segmentId = slice.ReadLongInt64()
	xdes.xdesListNode = ListNodeReadSlice()
	xdes.state = XdesStateFind(slice.ReadInt())
	xdes.pageStateBitmap = slice.ReadByteArray(16)
	return xdes
}

func XdesStateFind(state int64) XdesState {
	var xs XdesState
	if state == FREE {
		xs = "FREE"
	} else if state == FREE_FRAG {
		xs = "FREE_FRAG"
	} else if state == FULL_FRAG {
		xs = "FULL_FRAG"
	} else if state == FSEG {
		xs = "FSEG"
	} else {
		xs = ""
	}
	return xs
}
